package com.easybuilder.common.utils;

import com.easybuilder.common.base.entity.PageResultWrapper;
import com.github.pagehelper.Page;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 分页查询工具类
 *
 * @author 张兴帅
 * @projectName easy-builder
 * @packageNmae com.easybuilder.common.utils
 * @fileNmae PageUtil
 * @date 2023-5-16
 * @copyright 华能信息技术有限公司
 * @since 0.0.1
 */
public class PageUtil {

    public static <T> PageResultWrapper<T> build(Page<Object> page){
        List<T> list = (List<T>) page.getResult();
        PageResultWrapper<T> pageResult = new PageResultWrapper<>(page.getPageNum(),page.getPageSize(),
                page.getTotal(),list);
        return pageResult;
    }

    public static <T> Example buildExample(T searchEntity, Class<T> clazz) {
        Example example = new Example(clazz);
        if (searchEntity != null) {
            Example.Criteria criteria = example.createCriteria();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                String fieldName = field.getName();
                try {
                    field.setAccessible(true);
                    Object value = field.get(searchEntity);
                    //TODO 此次需要根据字段类型，选择合适的比对条件（=、>=、<=、between and、 like）
                    if (value != null) {
                        criteria.andEqualTo(fieldName, value);
                    }
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        example.orderBy("createTime");
        return example;
    }
}